{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Interactive visualization of MPI simulaitons"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In this example, which builds on our previous one of interactive MPI monitoring, we now demonstrate how to use the IPython data publication APIs."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Load IPython support for working with MPI tasks"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If you have not done so yet, use [the cluster tab in the Dashboard](/#tab2) to start your `mpi` cluster, it should be OK to leave the number of engines field empty (IPython will auto-detect the number of cores on your machine), unless you want to limit the run to use less cores than available in total.  Once your MPI cluster is running, you can proceed with the rest of the code.\n",
    "\n",
    "We begin by creating a cluster client that gives us a local handle on the engines running in the (possibly remote) MPI cluster.  From the client we make a `view` object, which we set to use blocking mode by default as it is more convenient for interactive control.  Since the real computation will be done over MPI without IPython intervention, setting the default behavior to be blocking will have no significant performance impact.\n",
    "\n",
    "**Note:** if on first try the following cell gives you an error message, wait a few seconds and run it again. It's possible that the system is simply initializing all your MPI engines, which may take a bit of time to be completely ready if you hadn't used any MPI libraries recently and the disk cache is cold."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import ipyparallel as ipp\n",
    "cluster = ipp.Client(profile=\"mpi\")\n",
    "view = cluster[:]\n",
    "view.block = True"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's also load the plotting and numerical libraries so we have them ready for visualization later on."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "%matplotlib inline\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now, we load the MPI libraries into the engine namespaces, and do a simple printing of their MPI rank information to verify that all nodes are operational and they match our cluster's real capacity.  \n",
    "\n",
    "Here, we are making use of IPython's special `%%px` cell magic, which marks the entire cell for parallel execution.  This means that the code below will not run in this notebook's kernel, but instead will be sent to *all* engines for execution there.  In this way, IPython makes it very natural to control your entire cluster from within the notebook environment:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[stdout:0] MPI rank: 2/4\n",
      "[stdout:1] MPI rank: 0/4\n",
      "[stdout:2] MPI rank: 3/4\n",
      "[stdout:3] MPI rank: 1/4\n"
     ]
    }
   ],
   "source": [
    "%%px\n",
    "# MPI initialization, library imports and sanity checks on all engines\n",
    "from mpi4py import MPI\n",
    "# Load data publication API so engines can send data to notebook client\n",
    "from ipyparallel.datapub import publish_data\n",
    "import numpy as np\n",
    "import time\n",
    "\n",
    "mpi = MPI.COMM_WORLD\n",
    "bcast = mpi.bcast\n",
    "barrier = mpi.barrier\n",
    "rank = mpi.rank\n",
    "print(\"MPI rank: %i/%i\" % (mpi.rank,mpi.size))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We write a utility that reorders a list according to the mpi ranks of the engines, since all gather operations will return data in engine id order, not in MPI rank order.  We'll need this later on when we want to reassemble in IPython data structures coming from all the engines: IPython will collect the data ordered by engine ID, but our code creates data structures based on MPI rank, so we need to map from one indexing scheme to the other.  This simple function does the job:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "ranks = view['rank']\n",
    "engine_mpi = np.argsort(ranks)\n",
    "\n",
    "def mpi_order(seq):\n",
    "    \"\"\"Return elements of a sequence ordered by MPI rank.\n",
    "\n",
    "    The input sequence is assumed to be ordered by engine ID.\"\"\"\n",
    "    return [seq[x] for x in engine_mpi]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## MPI simulation example"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This is our 'simulation', a toy example that computes $\\sin(f(x^2+y^2))$ for a slowly increasing frequency $f$ over a gradually refined mesh.  In a real-world example, there typically is a 'simulate' method that, afer setting up initial parameters, runs the entire computation.  But having this simple example will be sufficient to see something that changes visually as the computation evolves and that is quick enough for us to test.\n",
    "\n",
    "And while simple, this example has a realistic decomposition of the spatial domain in one array per MPI node that requires care in reordering the data for visualization, as would be needed in a real-world application (unless your code accumulates data in the rank 0 node that you can grab directly)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "%%px\n",
    "\n",
    "# Global flag in the namespace\n",
    "stop = False\n",
    "\n",
    "def simulation(nsteps=100, delay=0.1):\n",
    "    \"\"\"Toy simulation code, computes sin(f*(x**2+y**2)) for a slowly increasing f\n",
    "    over an increasingly fine mesh.\n",
    "\n",
    "    The purpose of this code is simply to illustrate the basic features of a typical\n",
    "    MPI code: spatial domain decomposition, a solution which is evolving in some \n",
    "    sense, and local per-node computation.  In this case the nodes only communicate when \n",
    "    gathering results for publication.\"\"\"\n",
    "    # Problem geometry\n",
    "    xmin, xmax = 0, np.pi\n",
    "    ymin, ymax = 0, 2*np.pi\n",
    "    dy = (ymax-ymin)/mpi.size\n",
    "\n",
    "    freqs = np.linspace(0.6, 1, nsteps)\n",
    "    for j in range(nsteps):\n",
    "        nx, ny = 2+j/4, 2+j/2/mpi.size\n",
    "        nyt = mpi.size*ny\n",
    "        Xax = np.linspace(xmin, xmax, nx)\n",
    "        Yax = np.linspace(ymin+rank*dy, ymin+(rank+1)*dy, ny, endpoint=rank==mpi.size)\n",
    "        X, Y = np.meshgrid(Xax, Yax)\n",
    "        f = freqs[j]\n",
    "        Z = np.cos(f*(X**2 + Y**2))\n",
    "        \n",
    "        # We are now going to publish data to the clients. We take advantage of fast\n",
    "        # MPI communications and gather the Z mesh at the rank 0 node in the Zcat variable:\n",
    "        Zcat = mpi.gather(Z, root=0)\n",
    "        if mpi.rank == 0:\n",
    "            # Then we use numpy's concatenation to construct a single numpy array with the\n",
    "            # full mesh that can be sent to the client for visualization:\n",
    "            Zcat = np.concatenate(Zcat)\n",
    "            # We now can send a dict with the variables we want the client to have access to:\n",
    "            publish_data(dict(Z=Zcat, nx=nx, nyt=nyt, j=j, nsteps=nsteps))\n",
    "            \n",
    "        # We add a small delay to simulate that a real-world computation\n",
    "        # would take much longer, and we ensure all nodes are synchronized\n",
    "        time.sleep(delay)\n",
    "        # The stop flag can be set remotely via IPython, allowing the simulation to be\n",
    "        # cleanly stopped from the outside\n",
    "        if stop:\n",
    "            break"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## IPython tools to interactively monitor and plot the MPI results"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We now define a local (to this notebook) plotting function that fetches data from the engines' global namespace.  Once it has retrieved the current state of the relevant variables, it produces and returns a figure:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "from IPython.display import display, clear_output\n",
    "\n",
    "def plot_current_results(ar, in_place=True):\n",
    "    \"\"\"Makes a blocking call to retrieve remote data and displays the solution mesh\n",
    "    as a contour plot.\n",
    "    \n",
    "    Parameters\n",
    "    ----------\n",
    "    ar : async result object\n",
    "\n",
    "    in_place : bool\n",
    "        By default it calls clear_output so that new plots replace old ones.  Set\n",
    "        to False to allow keeping of all previous outputs.\n",
    "    \"\"\"\n",
    "    # Read data from MPI rank 0 engine\n",
    "    data = ar.data[engine_mpi[0]]\n",
    "    \n",
    "    try:\n",
    "        nx, nyt, j, nsteps = [data[k] for k in ['nx', 'nyt', 'j', 'nsteps']]\n",
    "        Z = data['Z']\n",
    "    except KeyError:\n",
    "        # This can happen if we read from the engines so quickly that the data \n",
    "        # hasn't arrived yet.\n",
    "        fig, ax = plt.subplots()\n",
    "        ax.plot([])\n",
    "        ax.set_title(\"No data yet\")\n",
    "        display(fig)\n",
    "        return fig\n",
    "    else:\n",
    "    \n",
    "        fig, ax = plt.subplots()\n",
    "        ax.contourf(Z)\n",
    "        ax.set_title('Mesh: %i x %i, step %i/%i' % (nx, nyt, j+1, nsteps))\n",
    "        plt.axis('off')\n",
    "        # We clear the notebook output before plotting this if in-place \n",
    "        # plot updating is requested\n",
    "        if in_place:\n",
    "            clear_output(wait=True)\n",
    "        display(fig)\n",
    "        \n",
    "        return fig"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Finally, this is a convenience wrapper around the plotting code so that we can interrupt monitoring at any point, and that will provide basic timing information:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def monitor_simulation(ar, refresh=5.0, plots_in_place=True):\n",
    "    \"\"\"Monitor the simulation progress and call plotting routine.\n",
    "\n",
    "    Supress KeyboardInterrupt exception if interrupted, ensure that the last \n",
    "    figure is always displayed and provide basic timing and simulation status.\n",
    "\n",
    "    Parameters\n",
    "    ----------\n",
    "    ar : async result object\n",
    "\n",
    "    refresh : float\n",
    "      Refresh interval between calls to retrieve and plot data.  The default\n",
    "      is 5s, adjust depending on the desired refresh rate, but be aware that \n",
    "      very short intervals will start having a significant impact.\n",
    "\n",
    "    plots_in_place : bool\n",
    "       If true, every new figure replaces the last one, producing a (slow)\n",
    "       animation effect in the notebook.  If false, all frames are plotted\n",
    "       in sequence and appended in the output area.\n",
    "    \"\"\"\n",
    "    import datetime as dt, time\n",
    "    \n",
    "    if ar.ready():\n",
    "        plot_current_results(ar, in_place=plots_in_place)\n",
    "        plt.close('all')\n",
    "        print('Simulation has already finished, no monitoring to do.')\n",
    "        return\n",
    "    \n",
    "    t0 = dt.datetime.now()\n",
    "    fig = None\n",
    "    try:\n",
    "        while not ar.ready():\n",
    "            fig = plot_current_results(ar, in_place=plots_in_place)\n",
    "            plt.close('all') # prevent re-plot of old figures\n",
    "            time.sleep(refresh)\n",
    "    except (KeyboardInterrupt, ipp.error.TimeoutError):\n",
    "        msg = 'Monitoring interrupted, simulation is ongoing!'\n",
    "    else:\n",
    "        msg = 'Simulation completed!'\n",
    "    tmon = dt.datetime.now() - t0\n",
    "    if plots_in_place and fig is not None:\n",
    "        clear_output(wait=True)\n",
    "        plt.close('all')\n",
    "        display(fig)\n",
    "    print(msg)\n",
    "    print('Monitored for: %s.' % tmon)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Interactive monitoring in the client of the published data"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now, we can monitor the published data. We submit the simulation for execution as an asynchronous task, and then monitor this task at any frequency we desire."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# Create the local client that controls our IPython cluster with MPI support\n",
    "import ipyparallel as ipp\n",
    "cluster = ipp.Client(profile=\"mpi\")\n",
    "# We make a view that encompasses all the engines\n",
    "view = cluster[:]\n",
    "# And now we call on all available nodes our simulation routine,\n",
    "# as an asynchronous task\n",
    "ar = view.apply_async(lambda : simulation(nsteps=10, delay=0.1))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAk4AAAGKCAYAAAD6yM7KAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAGIZJREFUeJzt3XuQV3X9+PHXZ9W4SLYIISERuowojZKOoyRFhuYtFUPU\nMElMSZukpkgdhWrN+1iTZSEKKKGoQ+p4SR1RQi3FqEa3BiEV0dAcZxCRIkSXPd8//Lm/gF1473I+\n+7k9HjPMxOdzzvu8d9f2PDm3TyHLsiwAANiuulJPAACgUggnAIBEwgkAIJFwAgBIJJwAABIJJwCA\nRMIJqtwrr7wSe+21V6mnQQds2rSp1FMA2iGcoAs1NjZGXV1dXHfdde0uc88990RdXV2cddZZXTiz\nNC+++GKMGTMmevfuHZ/4xCdi4sSJ8eabb+a6jffeey+mTp0an/rUp6K+vj6OP/74eOGFF3LdRils\n3LgxTjvttPjkJz+5zeVee+21GD58+GavrVq1Kvbff/+YMGFCm+vMmTMnhg4dGj179ozPfOYz8dBD\nD+U2b2Bzwgm6WI8ePWL27Nntvj9r1qzo2bNnFAqFLpzV9q1bty6OPPLIGDhwYLz00kvx7LPPRnNz\nc5x00km5bueiiy6KhQsXxoIFC+KVV16J4cOHxzHHHBPr16/PdTtd6e23344vfelL8cwzz2z35zp7\n9uw47rjjWv/e1NQUI0aMiHXr1rW57h133BHTpk2LOXPmxJo1a+LKK6+MM844IxYvXpz71wEIJ+hS\nhUIhjj766Fi1alU888wzW73/2muvxcKFC+Pkk0+Ocnuo/5IlS2Lw4MHx61//Ovr06RP9+/eP2bNn\nx7PPPht/+9vfctvOzTffHNdee20MHTo06uvr44orroiIiEcffTS3bdTVde2vvnHjxkXfvn1j5syZ\n2/y5trS0xC233BLf/OY3IyLinXfeiSOOOCK++93vxje+8Y021/3Rj34Uv/rVr+Kzn/1sdO/ePY47\n7ri45JJL4tJLLy3a1wO1TDhBF9t1113j9NNPj1mzZm313s033xxHHnlkDBo0qAQz27Yjjzwynnji\nic1e69atW/To0SNaWlpy207Pnj23eq1QKLT5emeUIkhvvPHG+O1vfxsf+chHtrncww8/HHvvvXcM\nGTIkIiI+9rGPxR//+Me48MIL25z3ihUr4tVXX41jjjlms9ePPfbYWLRoUbz33nv5fRFARAgnKIlJ\nkybF/PnzNzv9lGVZzJkzp/Vow5b+/Oc/x8iRI6NHjx4xcODAuPzyyze7iPjBBx+MAw44IHr27BkH\nHHBALFy4cLP1n3zyyTj44IOjV69ecfDBB8fTTz+92fuHHHJIfP/73+/Q1/G73/0uIiL222+/Nt+/\n+OKLY999940NGza0fo2jR4+OqVOntjvm5MmT44ILLogXX3wx3nnnnZg2bVr06tUrjjjiiOR5vfnm\nmz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eHQ888ECcc845Wy33/vvvx5/+9KcYPXp01NXVtf7p3r17/Pe//41ly5bF\n/vvvH6NHj44hQ4bEWWedFbfddlts3LixdYy+fftudcpnr732irfeeqvD816/fn18+ctfjr59+8b8\n+fO3u/zgwYPj6quvjnPPPTfOP//8dk/rRUQ899xz8fvf/z7mzZsXDQ0NUV9fH+eff34cffTR8ctf\n/jJ5jlOmTInvfOc7cdRRR8XVV18dK1eu3Obyf/jDH2Lu3LmbfX/r6urilltuiWXLlrUuN2bMmDZP\nizU0NGx16rMjWlpa4uabb45JkyZ1aL3evXvHunXr2hxv3bp1sfvuu3d6TkDbhBOUyG677Rannnpq\nzJw5M+bOnRuf+9znWh9UueVt54VCIf7+979HS0vLZn82bdoUI0eOjEKhEPfff3888MAD0dDQEFde\neWWMGjUqmpubI+KDC9K3tMsuu3T4Qun3338/xo0bFy0tLfHQQw9tFRFtybIs5s+fH/vvv3/cdddd\nmwXdlpYvXx5DhgzZar4HHXRQLF++PHmep59+erz00ktx6qmnxuLFi2P48OFt3sX4obq6upgyZUqb\n398PT3kWCoVtfr925PERjzzySAwaNCiGDh3aofUaGhrixRdf3Op7unz58mhpadnuM6OAjhNO0IW2\n3LlOmjQpbr311pg1a1a7Rxt22WWXOOyww+K2227b7PVNmzbF0qVLW//e3NwcI0aMiGnTpkVTU1Ms\nW7Ys18cEZFkWEydOjNdffz0eeeSR6NWrV9J61157bWzYsCGWLFkSPXr0iO9973vtLrvnnnvGihUr\ntnpm07PPPhsDBw5Mnmtzc3MMGDAgzjnnnLjvvvti/PjxMW/evHaX/8IXvhB33333VgHS1NTU+r+z\nLIsHHngg3n333c2WWb58eaxYsSIOO+yw5Pltqa2LwrfUVpg1NDTE4MGDt3rg5YMPPhijR4/e7l18\nQMcJJ+hCWx6xGDFiRAwYMCBWr14dX/nKV9pd7uc//3lcf/318Ytf/CLWrFkTr7zySpx++ukxZcqU\niIh44oknYtiwYdHU1BTvvvtu3HvvvbFp06btxsb/bmfChAnbfKL51KlTY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dlwEhwAQEcVsizL\n8hjoqUIhj2EAAIpuZCfzx4f8AgAkEk4AAImEEwBAIuEEAJBIOAEAJBJOAACJhBMAQCLhBACQSDgB\nACQSTgAAiYQTAEAi4QQAkEg4AQAkEk4AAImEEwBAIuEEAJBIOAEAJBJOAACJhBMAQCLhBACQSDgB\nACQSTgAAiYQTAEAi4QQAkEg4AQAkEk4AAImEEwBAIuEEAJBIOAEAJBJOAACJhBMAQCLhBACQSDgB\nACQSTgAAiYQTAEAi4QQAkEg4AQAkEk4AAImEEwBAIuEEAJBIOAEAJBJOAACJhBMAQCLhBACQSDgB\nACQSTgAAiYQTAEAi4QQAkEg4AQAkEk4AAImEEwBAIuEEAJBIOAEAJBJOAACJhBMAQCLhBACQSDgB\nACQSTgAAiYQTAEAi4QQAkKiQZVlW6kkAAFQCR5wAABIJJwCARMIJACCRcAIASCScAAASCScAgETC\nCQAgkXACAEgknAAAEgknAIBEwgkAIJFwAgBIJJwAABIJJwCARMIJACCRcAIASCScAAASCScAgETC\nCQAgkXACAEgknAAAEgknAIBEwgkAINH/Acd8GCUQEYlkAAAAAElFTkSuQmCC\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x10b00b350>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Simulation completed!\n",
      "Monitored for: 0:00:01.229672.\n"
     ]
    }
   ],
   "source": [
    "monitor_simulation(ar, refresh=1)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
